#!/usr/bin/env bash

read -r -d '' DEFAULT_ASANFLAGS <<- EOF
-fsanitize=address,undefined
-fsanitize-recover=address,undefined
-fno-sanitize=vptr
-fno-omit-frame-pointer
-fuse-ld=gold
EOF
DEFAULT_ASANFLAGS="$(echo ${DEFAULT_ASANFLAGS} | tr '\n' ' ')"

: ${ASANFLAGS="${DEFAULT_ASANFLAGS}"}
: ${CC="gcc-6"}
: ${CXX="g++-6"}
: ${BUILD_DIR="gcc-ubsan-build"}
: ${MAKEFLAGS="-j8"}
: ${R_HOME="$(R RHOME)"}

# NOTE: Boost 1.50.0 not compatible with gcc-6
: ${RSTUDIO_USE_LIBCXX="No"}
: ${RSTUDIO_USE_SYSTEM_BOOST="Yes"}
: ${RSTUDIO_BOOST_VERSION="1.54.0"}

mkdir -p "${BUILD_DIR}"
cd "${BUILD_DIR}"
cmake ../cpp                                                 \
    -DLIBR_HOME="${R_HOME}"                                  \
    -DCMAKE_C_COMPILER="${CC}"                               \
    -DCMAKE_C_FLAGS="${ASANFLAGS} ${LDFLAGS}"                \
    -DCMAKE_CXX_COMPILER="${CXX}"                            \
    -DCMAKE_CXX_FLAGS="${ASANFLAGS} ${LDFLAGS}"              \
    -DRSTUDIO_USE_LIBCXX="${RSTUDIO_USE_LIBCXX}"             \
    -DRSTUDIO_USE_SYSTEM_BOOST="${RSTUDIO_USE_SYSTEM_BOOST}" \
    -DRSTUDIO_BOOST_VERSION="${RSTUDIO_BOOST_VERSION}"       \
    "$@"
cd ..

cmake --build "${BUILD_DIR}" -- "${MAKEFLAGS}"
